package com.yxy.controller;

import com.yxy.common.Result;
import com.yxy.context.BaseContext;
import com.yxy.pojo.dto.UserDTO;
import com.yxy.pojo.dto.UserInfoDTO;
import com.yxy.pojo.vo.UserInfoVO;
import com.yxy.pojo.vo.UserVO;
import com.yxy.properties.JwtProperties;
import com.yxy.service.UserService;
import com.yxy.utils.JwtUtils;
import com.yxy.utils.RandomVerifyCodeUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/bfbbs")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO){
        log.info("用户登录：{}", userDTO);
        UserVO vo = userService.login(userDTO);
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("nickname", vo.getNickName());
        claims.put("avatar", vo.getAvatar());
        claims.put("userId", vo.getId());
        // 生成JWT令牌
        String token = JwtUtils.createJwt(jwtProperties.getSignKey(), jwtProperties.getExpire(), claims);
        vo.setToken(token);
        return Result.success("登录成功",vo);
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("用户注册：{}", userDTO);
        userService.register(userDTO);
        return Result.success("注册成功",null);
    }

    /**
     * 获取验证码
     * @return
     */
    @GetMapping("/generateCaptcha")
    public Result getVerifyCode() {
        String captcha = RandomVerifyCodeUtil.generateRandomString();
        return Result.success(24, "验证码获取成功", captcha);
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfo/{userId}")
    public Result<UserInfoVO> getUserInfo(@PathVariable int userId){
        log.info("根据id查询用户信息：{}", userId);
        // 构造redis中key：规则：user_用户id
        String key = "user_" + userId;
        UserInfoVO redisUserVo = (UserInfoVO) redisTemplate.opsForValue().get(key);
        // 如果存在，直接返回，无需查询数据库
        if(redisUserVo != null){
            return Result.success("", redisUserVo);
        }
        // 如果不存在，则查询数据库，并保存到redis中
        UserInfoVO vo = userService.getByUserId(userId);
        redisTemplate.opsForValue().set(key, vo);
        return Result.success("", vo);
    }

    /**
     * 修改用户信息
     * @param userInfoDTO
     * @return
     */
    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserInfoDTO userInfoDTO){
        log.info("修改用户信息：{}", userInfoDTO);
        userService.updateUserInfo(userInfoDTO);
        // 删除redis缓存
        redisTemplate.delete("user_" + userInfoDTO.getId());
        return Result.success("修改成功", null);
    }

    /**
     * 校验密码
     * @param userInfoDTO
     * @return
     */
    @GetMapping("/checkPwd")
    public Result<Boolean> checkPwd(UserInfoDTO userInfoDTO) {
        log.info("校验密码：{}", userInfoDTO);
        Boolean flag = userService.checkPwd(userInfoDTO);
        return Result.success("", flag);
    }

    /**
     * 退出登录，删除redis中的用户信息
     * @return
     */
    @DeleteMapping("/logout")
    public Result<String> exitLogin(){
        log.info("退出登录");
        Integer userId = BaseContext.getCurrentId();
        System.out.println(userId);
        redisTemplate.delete("user_" + userId);
        return Result.success("退出成功", null);
    }
}
